package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.event.FinishEvent;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.SingleInputEvent;
import com.onenine.app.model.GroupMemberItem;
import com.onenine.app.request.EditGroupNameRequest;
import com.onenine.app.request.EditGroupNoInterruptionRequest;
import com.onenine.app.request.GroupMemberRequest;
import com.onenine.app.response.BlnResponse;
import com.onenine.app.response.GroupMemberResponse;
import com.onenine.app.response.GroupOwnerResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.SwitchButton;
import com.onenine.chat.model.LGroup;
import com.onenine.chat.rongcloud.GroupCacheMgr;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.rong.message.GroupNotificationMessage;

/**
 * 创建时间：2018/6/23 0023 16:14
 * 创建人：fly
 * 功能描述：群组选项
 */
public class GroupOptionActivity extends BaseEventActivity implements View.OnClickListener, SwitchButton.OnCheckedChangeListener {

    //最大显示13个成员
    private static final int MAX_MEMBER_SHOW_COUNT = 13;
    private TextView mTvReport, mTvGroupName;
    private FlexboxLayout mFlexLayout;
    private Button mBtnMore;
    private TextView mTvQuit;
    private SwitchButton mBtnSwitch;
    private String mGroupChatId;
    private boolean isGroupOwner;

    public static void launchActivity(Context context, String groupId) {
        Intent intent = new Intent(context, GroupOptionActivity.class);
        intent.putExtra("groupId", groupId);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_group_option;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setCenterTitle(R.string.chat_info);
        mTvReport = findViewById(R.id.tv_report_group);
        mTvQuit = findViewById(R.id.btn_quit);
        mTvGroupName = findViewById(R.id.tv_group_name);
        mFlexLayout = findViewById(R.id.fb_member);
        mBtnMore = findViewById(R.id.btn_more_member);
        mBtnSwitch = findViewById(R.id.btn_msg_no_interrupt);
        int roleColor = RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR);
        mBtnSwitch.setCheckedColor(roleColor);
        mTvQuit.setTextColor(roleColor);
    }

    @Override
    protected void initListeners() {
        mTvReport.setOnClickListener(this);
        mTvQuit.setOnClickListener(this);
        mBtnMore.setOnClickListener(this);
        mTvGroupName.setOnClickListener(this);
        mBtnSwitch.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        mGroupChatId = getIntent()
                .getStringExtra("groupId");
        if (TextUtils.isEmpty(mGroupChatId)) {
            finish();
        } else {
            getGroupInfo();
            queryGroupMemberOwner();
        }
    }

    /**
     * 获取群基本信息
     */
    private void getGroupInfo() {
        GroupCacheMgr.getInstance().getGroupAsync(mGroupChatId, new GroupCacheMgr.OnGroupCallback() {
            @Override
            public void callback(LGroup group) {
                if (group != null) {
                    mTvGroupName.setText(group.getGroupName());
                    mBtnSwitch.setChecked(group.getNoDisturb() > 0);
                }
            }
        });
    }

    /**
     * 查询成员列表
     */
    private void queryGroupMemberList() {
        OkRequest.getInstance().withUrl(UrlConfig.GET_GROUP_MEMBER_LIST)
                .withRequest(new GroupMemberRequest(RcUser.getInstance().getUserId(), mGroupChatId))
                .doRequest(GroupMemberActivity.class.getSimpleName(), new OkCallback<GroupMemberResponse>() {
                    @Override
                    public void onResponse(GroupMemberResponse response, String srcData) {
                        if (response.isSuccess()) {
                            showGroupMemberView(response.getGroupMemberList());
                        } else {
                            Toasty.showNormal("群成员加载失败");
                            finish();
                        }
                    }
                });
    }

    /**
     * 展示成员网络
     *
     * @param groupMemberItems
     */
    private void showGroupMemberView(List<GroupMemberItem> groupMemberItems) {
        if (groupMemberItems.size() > MAX_MEMBER_SHOW_COUNT) {
            mBtnMore.setVisibility(View.VISIBLE);
            groupMemberItems = groupMemberItems.subList(0, MAX_MEMBER_SHOW_COUNT);
        }
        for (GroupMemberItem item : groupMemberItems) {
            addItemView(item.getUserId(), item.getNickName(), item.getPhoto());
        }
        addItemView("", "", "+");
        if (isGroupOwner) {
            addItemView("", "", "-");
        }
    }

    /**
     * 加入单人项
     *
     * @param userId
     * @param name
     * @param photo
     */
    private void addItemView(final String userId, String name, final String photo) {
        int margin = SizeUtils.dp2px(5);
        int itemSize = (mFlexLayout.getWidth() - 10 * margin) / 5;
        FlexboxLayout.LayoutParams itemParams = new FlexboxLayout.LayoutParams(itemSize, FlexboxLayout.LayoutParams.WRAP_CONTENT);
        itemParams.setMargins(margin, margin, margin, margin);
        LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(itemSize, LinearLayout.LayoutParams.WRAP_CONTENT);
        textParams.setMargins(0, SizeUtils.dp2px(10), 0, 0);
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(itemSize, itemSize);
        View itemView = LayoutInflater.from(this).inflate(R.layout.layout_group_member_item, null, false);
        ImageView imageView = itemView.findViewById(R.id.iv_avatar);
        imageView.setLayoutParams(imageParams);
        if ("+".equals(photo)) {
            //加号
            imageView.setImageResource(R.drawable.ic_circle_add);
        } else if ("-".equals(photo)) {
            //减号
            imageView.setImageResource(R.drawable.ic_circle_delete);
        } else {
            GlideUtils.loadSrcImage(ApUtils.getApp(), imageView, photo);
        }
        TextView tvName = itemView.findViewById(R.id.tv_name);
        tvName.setText(name);
        tvName.setLayoutParams(textParams);
        mFlexLayout.addView(itemView, itemParams);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("+".equals(photo)) {
                    GroupMemberMgrActivity.launchActivity(GroupOptionActivity
                            .this, mGroupChatId, GroupMemberMgrActivity.INVITE);
                } else if ("-".equals(photo)) {
                    GroupMemberMgrActivity.launchActivity(GroupOptionActivity
                            .this, mGroupChatId, GroupMemberMgrActivity.KICK);
                } else {
                    UserDetailActivity.launchActivity(GroupOptionActivity.this, userId);
                }
            }
        });
    }

    /**
     * 查询是否为群组
     */
    private void queryGroupMemberOwner() {
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_MEMBER_IS_GROUP_OWNER)
                .withRequest(new GroupMemberRequest(RcUser.getInstance().getUserId(), mGroupChatId))
                .doRequest(GroupOptionActivity.class.getSimpleName(), new OkCallback<GroupOwnerResponse>() {
                    @Override
                    public void onResponse(GroupOwnerResponse response, String srcData) {
                        if (response.isSuccess()) {
                            isGroupOwner = response.isBln();
                            mTvQuit.setText(isGroupOwner ? R.string.destroy_group : R.string.quit);
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                        queryGroupMemberList();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_report_group:
                ReportOptionActivity.launchActivity(GroupOptionActivity.this
                        , DataType.REPORT_GROUP, mGroupChatId);
                break;
            case R.id.btn_more_member:
                GroupMemberActivity.launchActivity(this, mGroupChatId);
                break;
            case R.id.btn_quit:
                quitGroupChat();
                break;
            case R.id.tv_group_name:
                if (!isGroupOwner) {
                    return;
                }
                //修改群名称
                SingleInputEvent inputEvent = new SingleInputEvent();
                inputEvent.type = 1;
                inputEvent.maxLength = 10;
                inputEvent.preResult = mTvGroupName.getText().toString();
                inputEvent.title = getString(R.string.edit_group_name);
                inputEvent.titleHint = "";
                SingleInputActivity.launchActivity(this, inputEvent);
                break;
        }
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        editNoInterruption(isChecked);
    }

    /**
     * 编辑免打扰
     */
    private void editNoInterruption(final boolean isChecked) {
        EditGroupNoInterruptionRequest request = new EditGroupNoInterruptionRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setGroupChatId(mGroupChatId);
        request.setNoDisturb(isChecked ? 1 : 0);
        OkRequest.getInstance().withRequest(request).withUrl(UrlConfig.EDIT_NO_INTERRUPTION)
                .doRequest(GroupOptionActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            EventBus.getDefault().post(new MessageNotifyEvent(DataType.COMMON_NOTIFY_MSG));
                            GroupCacheMgr.getInstance().refreshGroupAsync(mGroupChatId);
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 退出群聊
     */
    private void quitGroupChat() {
        OkRequest.getInstance().withUrl(isGroupOwner ? UrlConfig.DESTROY_GROUP : UrlConfig.QUIT_GROUP)
                .withRequest(new GroupMemberRequest(RcUser.getInstance().getUserId(), mGroupChatId))
                .doRequest(GroupOptionActivity.class.getSimpleName(), new OkCallback<BlnResponse>() {
                    @Override
                    public void onResponse(BlnResponse response, String srcData) {
                        if (response.isSuccess()) {
                            GroupNotificationMessage message = GroupNotificationMessage.obtain(RcUser.getInstance().getUserId()
                                    , GroupNotificationMessage.GROUP_OPERATION_DISMISS, mGroupChatId, null);
                            EventBus.getDefault().post(message);
                            Toasty.showNormal(R.string.quit_success);
                            finish();
                        } else {
                            Toasty.showNormal(R.string.quit_failure);
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FinishEvent event) {
        if (event.isFinish) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SingleInputEvent event) {
        if (event.type == 1 && !TextUtils.equals(mTvGroupName
                .getText().toString(), event.latestResult)) {
            EditGroupName(event.latestResult);
        }
    }

    /**
     * 编辑名称
     *
     * @param newName
     */
    private void EditGroupName(final String newName) {
        EditGroupNameRequest request = new EditGroupNameRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setGroupChatId(mGroupChatId);
        request.setChatName(newName);
        OkRequest.getInstance().withRequest(request).withUrl(UrlConfig.EDIT_GROUP_NAME)
                .doRequest(GroupOptionActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            GroupNotificationMessage notificationMessage = GroupNotificationMessage.obtain(RcUser.getInstance().getUserId()
                                    , GroupNotificationMessage.GROUP_OPERATION_RENAME, newName, getString(R.string.edit_group_new_name_format, newName));
                            EventBus.getDefault().post(notificationMessage);
                            GroupCacheMgr.getInstance().refreshGroupAsync(mGroupChatId);
                            mTvGroupName.setText(newName);
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

}
